/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.common  
 */
package com.apache.bid.controller;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apache.api.entity.BaseEntity;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.manager.UnityBaseManager;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.entity.User;

/**
 * description:  竞价系统父类action
 * @author Hou Dayu 创建时间：2016-3-14  
 * 
 */
public abstract class BaseSupperAction<T extends BaseEntity> {

	protected Logger logger = Logger.getLogger(this.getClass());

	protected abstract UnityBaseManager<T> getBaseManager();

	protected abstract String getCommBoxValue(T item, String type);

	/**
	 *查询列表分页数据，返回JSON数据
	 */
	@RequestMapping(value = { "/rf" }, method = { RequestMethod.GET })
	@ResponseBody
	protected Object listData(HttpServletRequest request, @ModelAttribute T item, String page, String rows) {
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setObj(item);
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (Validator.isNotNull(rows)) {//rows为空表示不进行分页处理
			vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
			vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
			Page pageList = getBaseManager().getPageInfo(vo);//分页
			mapData.put("total", pageList.getCount());//dataGrid所需参数
			mapData.put("rows", pageList.getPageObjects());//dataGrid所需数据对象集合
		} else {
			List<T> list = getBaseManager().getList(vo);
			if (!Validator.isEmpty(list)) {
				mapData.put("total", list.size());//dataGrid所需参数
				mapData.put("rows", list);//dataGrid所需数据对象集合
			}
		}
		return mapData;
	}

	/**
	 *查询单个对象，返回JSON数据
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.GET })
	@ResponseBody
	protected Object infoData(@PathVariable String id, HttpServletRequest request) {
		Map<String, Object> mapData = new HashMap<String, Object>();
		T item = null;
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		item = (T) getBaseManager().getInfoById(vo);
		mapData.put("flag", "T");
		mapData.put("msg", "查询成功！");
		mapData.put("item", item);
		return mapData;
	}

	/**
	 * 保存Session
	 */
	@RequestMapping(value = { "/rf" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultMsg saveInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute T item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");

		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setParams("loginUser", PBOSSOTools.getLoginUser(request));//存放当前登录用户
		vo.setObj(item);//新增
		String id = getBaseManager().saveInfo(vo);
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "新增条目失败，请重试!");
		}
		return rmsg;
	}

	/**
	 * 修改Session  
	 */
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.PUT })
	@ResponseBody
	public ResultMsg editInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute T item,
			@PathVariable String id) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "sessionId不能为空！");
			return rmsg;
		}

		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setObj(item);//修改
		boolean mark = getBaseManager().editInfo(vo);
		if (!mark) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	/**
	 * 根据id删除session表信息
	 */
	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.DELETE })
	@ResponseBody
	public ResultMsg deleteInfo(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
		//初始化结果提示信息
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		response.setContentType("text/html");
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "缺少必要的参数!");
			return rmsg;
		}
		ParamsVo<T> vo = new ParamsVo<T>();
		vo.setInfoId(id);
		vo.setParams("isDelete", "true");
		boolean mark = getBaseManager().deleteInfo(vo);
		if (!mark) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	@RequestMapping(value = { "/select" }, method = { RequestMethod.POST })
	@ResponseBody
	public JSONArray selectData(HttpServletRequest request, T item) {
		ParamsVo<T> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setObj(item);//新增
		List<T> list = getBaseManager().getList(vo);
		JSONArray jary = new JSONArray();
		//		JSONObject nvo = new JSONObject();
		//		nvo.put("id", "");
		//		nvo.put("text", "--请选择--");
		//		jary.add(nvo);
		if (!Validator.isEmpty(list)) {
			for (T obj : list) {
				JSONObject jvo = new JSONObject();
				jvo.put("id", getCommBoxValue(obj, "id"));
				jvo.put("text", getCommBoxValue(obj, "text"));
				jary.add(jvo);
			}
		}
		return jary;
	}

	protected ResultMsg getResultMsg(HttpServletRequest request, String msg) {
		request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
		ResultMsg rmsg = new ResultMsg("F", msg);
		return rmsg;
	}

	protected User getSessionUser(HttpServletRequest request) {
		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		if (!Validator.isEmpty(loginUser)) {
			return loginUser.getUser();
		}
		return null;
	}

	/**
	 * description:  日志生成调用方法
	 * @param request
	 */
	protected ParamsVo<T> getParamsVo(HttpServletRequest request) {
		ParamsVo<T> params = new ParamsVo<T>();
		params.setParams("logIp", getUserIp(request));
		params.setLogClassName(getGenType().trim());
		User user = getSessionUser(request);
		if (null == user)
			return params;
		params.setUserEname(user.getUserEname());
		params.setUserId(user.getUserId());
		return params;
	}

	/**
	 * description:  获取访问IP
	 * @param request 当前请求
	 * @return   
	 * @author Hou Dayu  
	 */
	protected String getUserIp(HttpServletRequest request) {
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (Validator.isNotNull(ip) && ip.length() > 32) {
				ip = ip.substring(0, 32);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ip;
	}

	protected String getGenType() {
		Type genType = getClass().getGenericSuperclass();
		Type[] ddd = ((ParameterizedType) genType).getActualTypeArguments();
		String className = ddd[0].toString().replaceAll("class", "");
		return className.toString();
	}
}
